package br.com.ciandt.android.bd.dao.impl;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteStatement;
import br.com.ciandt.android.bd.DataHelper;
import br.com.ciandt.android.bd.FactoryDataHelper;
import br.com.ciandt.android.bd.dao.PodCastFileDao;
import br.com.ciandt.android.to.Nota;
import br.com.ciandt.android.to.PodCastFile;

/**
 * 
 * @author kanjih
 *
 */
public class PodCastFileDaoImpl implements PodCastFileDao {
	
	private PodCastFile podCastFile;
	private DataHelper dataHelper;
	
	private static final String TABLE_NAME = "PODCAST_FILE";
	
	private SQLiteStatement insertStmt;
	private static final String INSERT = "insert into " + TABLE_NAME + "(ID_PODCAST, URL, NOVO, ATIVO, NOTA, FAVORITOS) values (?,?,?,?,?,?)";
	
	
	public PodCastFileDaoImpl(Context context) {
		this.dataHelper = FactoryDataHelper.getInstanceHelper(context);
		this.insertStmt = dataHelper.getDb().compileStatement(INSERT);
	}
	
	public PodCastFileDaoImpl(Context context, PodCastFile podCastFile) {
		this.dataHelper = FactoryDataHelper.getInstanceHelper(context);
		this.podCastFile = podCastFile;
	}

	@Override
	public List<PodCastFile> selectAll() {
		List<PodCastFile> lst = new ArrayList<PodCastFile>();
		Cursor cursor = dataHelper.getDb().query(TABLE_NAME, new String[]{"ID", "ID_PODCAST", "URL", "NOVO", "ATIVO", "NOTA", "FAVORITOS" }, 
				null, null, null, null, "ID DESC");
		while(!cursor.isAfterLast()) {
			if(cursor.getPosition() == -1) {
				cursor.moveToFirst();
			}
			PodCastFile podFile = new PodCastFile();
			podFile.setId(cursor.getLong(0));
			//podFile.setPodCast(cursor.getInt(1))
			podFile.setUrl(cursor.getString(2));
			podFile.setNovo(cursor.getInt(3) == 0 ? Boolean.FALSE : Boolean.TRUE);
			podFile.setAtivo(cursor.getInt(4) == 0 ? Boolean.FALSE : Boolean.TRUE);
			podFile.setNota(Nota.values()[cursor.getInt(5)]);
			podFile.setFavoritos(cursor.getInt(6) == 0 ? Boolean.FALSE : Boolean.TRUE);
			
			lst.add(podFile);
			cursor.moveToNext();
		}
		return lst;
	}

	@Override
	public void insert(PodCastFile to) {
		this.insertStmt.bindLong(1, to.getPodCast().getId());
		this.insertStmt.bindString(2, to.getUrl());
		this.insertStmt.bindLong(3, to.getNovo() ? 1 : 0);
		this.insertStmt.bindLong(4, to.getAtivo() ? 1 : 0);
		this.insertStmt.bindLong(5, to.getNota().ordinal());
		this.insertStmt.bindLong(6, to.getFavoritos() ? 1 : 0);
		this.insertStmt.executeInsert();
	}

}
